# -*- coding: utf-8 -*-
# @Time    : 2018-08-18 10:25
# @Author  : Yang Feng
# @Email   : yangfeng@bbdservice.com
# @File    : Ind_extention.py
# @Software: PyCharm


'''eof
name:个人特殊交易（展期）次数
code:Ind_extention
tableName:
columnName:
groups:准入>个人征信
dependencies:IC
type:常用指标
datasourceType:在线指标
description:
eof'''


import sys
import json
import datetime
import re
reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', None, 'null', '/', 'Null']


def FormatData(tableName):
    try:
        icr = json.loads(IC[0]["icr"])[tableName]
        return icr if isinstance(icr, list) and len(icr) > 0 else [{}]
    except:
        return [{}]


def JudgeExtention(dataList):
    resultList = []
    try:
        for dataItem in dataList:
            try:
                tradeType = dataItem.get("TradeType")
                if tradeType in null_type_list:
                    resultList.append(None)
                    continue
                if u"展期" in tradeType:
                    resultList.append(1)
                else:
                    resultList.append(0)
            except:
                resultList.append(None)
                continue
    except:
        resultList.append(None)
    return resultList


def IndExtention():
    try:
        returnList = []
        # 贷款特殊交易
        icrSpecialTradeLoanList = FormatData("ICRSpecialTrade*Loan")
        # 贷记卡特殊交易
        icrSpecialTradeCardList = FormatData("ICRSpecialTrade*Card")
        # 准贷记卡特殊交易
        icrSpecialTradeStdList = FormatData("ICRSpecialTrade*Std")
        if icrSpecialTradeLoanList == [{}] and icrSpecialTradeCardList == [{}] and icrSpecialTradeStdList == [{}]:
            return u"缺失值"
        returnList.extend(JudgeExtention(icrSpecialTradeLoanList))
        returnList.extend(JudgeExtention(icrSpecialTradeCardList))
        returnList.extend(JudgeExtention(icrSpecialTradeStdList))
        returnListNotNone = filter(lambda x: x is not None, returnList)
        if len(returnListNotNone) == 0:
            return u'缺失值'
        else:
            return sum(returnListNotNone)
    except:
        return u"缺失值"

result = IndExtention()